/*
 * @Author: NtyAaron
 * @Date: 2021-04-07 14:00:15
 * @LastEditors: NtyAaron
 * @LastEditTime: 2021-06-23 14:24:35
 * @Description: 封装request
 * @FilePath: \dwq\utils\request.js
 */
import { _t, _type } from '../i18n/base'
// import Toast from '../miniprogram_npm/@vant/weapp/toast/toast'
const app = getApp()
let loadingCount = 0

function addLoading() {
  wx.showLoading({
    title: _t()['加载中'],
  })
  loadingCount++
}

function isCloseLoading() {
  loadingCount--
  if (loadingCount == 0) {
    wx.hideLoading()
  }
}

function request(e) {
  addLoading()
  return new Promise((resolve, reject) => {
    let lang = wx.getStorageSync('language')
    wx.request({
      url: app.globalData.host + e.url,
      method: e.method || 'GET',
      data: e.data,
      header: {
        LANG: lang,
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        isCloseLoading()
        if (res.data.code == 201) {
          if (res.data.description) {
            if (e.url != '/stay/saveStay') {
              wx.showToast({
                title: res.data.description,
                icon: 'none',
              })
            }
          }
        }
        resolve(res.data)
      },
      fail: (err) => {
        isCloseLoading()
        reject(err)
      },
    })
  })
}
export default request
